package com.dev.ac.service.impl;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dev.ac.common.Const;
import com.dev.ac.entity.AAdmin;
import com.dev.ac.entity.ARole;
import com.dev.ac.service.AAdminService;
import com.dev.ac.mapper.AAdminMapper;
import com.dev.ac.service.ARoleService;
import com.dev.ac.util.JwtUtil;
import com.dev.ac.util.RedisUtil;
import com.dev.ac.vo.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;

/**
 * @author object
 * @description 针对表【a_admin】的数据库操作Service实现
 * @createDate 2024-04-14 16:13:23
 */
@Service
public class AAdminServiceImpl extends ServiceImpl<AAdminMapper, AAdmin>
		implements AAdminService {

	@Autowired
	HttpSession httpSession;
	@Autowired
	RedisUtil redisUtil;
	@Autowired
	JwtUtil jwtUtil;
	@Autowired
	ARoleService aRoleService;

	/**
	 * 获取当前登录对象的id
	 *
	 * @return
	 */
	@Override
	public Integer getCurrentId() {
		return (Integer) httpSession.getAttribute("username");
	}

	@Override
	public AAdmin getCurrentUser() {
		Integer username = (Integer) httpSession.getAttribute("username");

		AAdmin aAdmin = this.getById(username);
		Assert.notNull(aAdmin, "抱歉，未登录");
		return aAdmin;
	}

	@Override
	public Object login(LoginVo loginVo) {
		AAdmin username = this.getOne(new QueryWrapper<AAdmin>()
				.eq("username", loginVo.getUsername())
		);

		ARole aRole = aRoleService.getById(username.getRoleId());
		Assert.isTrue(aRole.getStatus() == 0, "抱歉，当前账号已被禁用");
		Assert.notNull(username, "抱歉，账号或密码错误");
		Assert.isTrue(username.getPassword().equals(loginVo.getPassword()), "抱歉，账号或密码错误");

		boolean equals = redisUtil.get(loginVo.getUuid()).equals(loginVo.getCode());
		Assert.isTrue(equals, "抱歉，验证码错误");
		Assert.isTrue(username.getIsDelete()==0, "抱歉，当前账号已禁用");
		String token = jwtUtil.generateToken(username.getId(), Const.GRADE_ADMIN);


		return MapUtil.builder()
				.put("adminInfo", username)
				.put("token", token)
				.build();
	}


}




